class SnakeGame {
    constructor() {
        this.canvas = document.getElementById('gameCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.scoreElement = document.getElementById('currentScore');
        this.statusElement = document.getElementById('gameStatus');
        
        this.gridSize = 16; // 适合400px画布的网格大小
        this.tileCount = Math.floor(this.canvas.width / this.gridSize);
        
        this.reset();
        this.setupEventListeners();
        this.draw();
    }
    
    reset() {
        const centerPos = Math.floor(this.tileCount / 2);
        this.snake = [
            {x: centerPos, y: centerPos}
        ];
        this.dx = 0;
        this.dy = 0;
        this.food = this.generateFood();
        this.score = 0;
        this.gameRunning = false;
        this.gamePaused = false;
        this.updateScore();
        this.updateStatus('按空格键或点击开始游戏按钮开始');
    }
    
    generateFood() {
        let food;
        do {
            food = {
                x: Math.floor(Math.random() * this.tileCount),
                y: Math.floor(Math.random() * this.tileCount)
            };
        } while (this.snake.some(segment => segment.x === food.x && segment.y === food.y));
        return food;
    }
    
    setupEventListeners() {
        document.addEventListener('keydown', (e) => {
            if (e.code === 'Space') {
                e.preventDefault();
                if (!this.gameRunning) {
                    this.startGame();
                } else if (this.gamePaused) {
                    this.resumeGame();
                } else {
                    this.pauseGame();
                }
            } else if (this.gameRunning && !this.gamePaused) {
                this.changeDirection(e);
            }
        });
    }
    
    changeDirection(e) {
        const LEFT_KEY = 37;
        const RIGHT_KEY = 39;
        const UP_KEY = 38;
        const DOWN_KEY = 40;
        
        const keyPressed = e.keyCode;
        const goingUp = this.dy === -1;
        const goingDown = this.dy === 1;
        const goingRight = this.dx === 1;
        const goingLeft = this.dx === -1;
        
        if (keyPressed === LEFT_KEY && !goingRight) {
            this.dx = -1;
            this.dy = 0;
        }
        if (keyPressed === UP_KEY && !goingDown) {
            this.dx = 0;
            this.dy = -1;
        }
        if (keyPressed === RIGHT_KEY && !goingLeft) {
            this.dx = 1;
            this.dy = 0;
        }
        if (keyPressed === DOWN_KEY && !goingUp) {
            this.dx = 0;
            this.dy = 1;
        }
    }
    
    startGame() {
        if (this.gameRunning) return;
        
        this.gameRunning = true;
        this.gamePaused = false;
        this.dx = 1;
        this.dy = 0;
        this.updateStatus('游戏进行中...');
        this.updateButtons();
        this.gameLoop();
    }
    
    pauseGame() {
        if (!this.gameRunning || this.gamePaused) return;
        
        this.gamePaused = true;
        this.updateStatus('游戏已暂停');
        this.updateButtons();
    }
    
    resumeGame() {
        if (!this.gamePaused) return;
        
        this.gamePaused = false;
        this.updateStatus('游戏进行中...');
        this.updateButtons();
        this.gameLoop();
    }
    
    resetGame() {
        this.reset();
        this.updateButtons();
    }
    
    updateButtons() {
        const startBtn = document.getElementById('startBtn');
        const pauseBtn = document.getElementById('pauseBtn');
        
        startBtn.disabled = this.gameRunning && !this.gamePaused;
        pauseBtn.disabled = !this.gameRunning || this.gamePaused;
    }
    
    gameLoop() {
        if (!this.gameRunning || this.gamePaused) return;
        
        this.clearCanvas();
        this.moveSnake();
        
        if (this.checkCollision()) {
            this.endGame();
            return;
        }
        
        this.checkFood();
        this.draw();
        
        setTimeout(() => this.gameLoop(), 100);
    }
    
    clearCanvas() {
        this.ctx.fillStyle = '#f9f9f9';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    }
    
    moveSnake() {
        const head = {x: this.snake[0].x + this.dx, y: this.snake[0].y + this.dy};
        this.snake.unshift(head);
        
        if (!this.eatingFood) {
            this.snake.pop();
        }
        this.eatingFood = false;
    }
    
    checkCollision() {
        const head = this.snake[0];
        
        // 检查墙壁碰撞
        if (head.x < 0 || head.x >= this.tileCount || 
            head.y < 0 || head.y >= this.tileCount) {
            return true;
        }
        
        // 检查自身碰撞
        for (let i = 1; i < this.snake.length; i++) {
            if (head.x === this.snake[i].x && head.y === this.snake[i].y) {
                return true;
            }
        }
        
        return false;
    }
    
    checkFood() {
        const head = this.snake[0];
        
        if (head.x === this.food.x && head.y === this.food.y) {
            this.score += 10;
            this.updateScore();
            this.food = this.generateFood();
            this.eatingFood = true;
        }
    }
    
    draw() {
        // 绘制蛇
        this.ctx.fillStyle = '#4CAF50';
        this.snake.forEach((segment, index) => {
            if (index === 0) {
                this.ctx.fillStyle = '#45a049'; // 蛇头颜色更深
            } else {
                this.ctx.fillStyle = '#4CAF50';
            }
            this.ctx.fillRect(
                segment.x * this.gridSize,
                segment.y * this.gridSize,
                this.gridSize - 2,
                this.gridSize - 2
            );
        });
        
        // 绘制食物
        this.ctx.fillStyle = '#ff6b6b';
        this.ctx.fillRect(
            this.food.x * this.gridSize,
            this.food.y * this.gridSize,
            this.gridSize - 2,
            this.gridSize - 2
        );
        
        // 绘制网格
        this.ctx.strokeStyle = '#ddd';
        this.ctx.lineWidth = 1;
        for (let i = 0; i <= this.tileCount; i++) {
            this.ctx.beginPath();
            this.ctx.moveTo(i * this.gridSize, 0);
            this.ctx.lineTo(i * this.gridSize, this.canvas.height);
            this.ctx.stroke();
            
            this.ctx.beginPath();
            this.ctx.moveTo(0, i * this.gridSize);
            this.ctx.lineTo(this.canvas.width, i * this.gridSize);
            this.ctx.stroke();
        }
    }
    
    updateScore() {
        this.scoreElement.textContent = this.score;
    }
    
    updateStatus(message) {
        this.statusElement.textContent = message;
    }
    
    endGame() {
        this.gameRunning = false;
        this.updateStatus('游戏结束！');
        this.updateButtons();
        
        // 显示游戏结束弹窗
        const finalScore = this.score;
        const highestScore = parseInt(localStorage.getItem('highestScore') || '0');
        const isNewRecord = finalScore > highestScore;
        
        if (isNewRecord) {
            localStorage.setItem('highestScore', finalScore);
            document.getElementById('gameHighestScore').textContent = finalScore;
        }
        
        document.getElementById('finalScore').textContent = finalScore;
        document.getElementById('newRecordText').style.display = isNewRecord ? 'block' : 'none';
        document.getElementById('gameOverModal').style.display = 'flex';
        
        // 保存游戏结果到服务器
        if (localStorage.getItem('token')) {
            saveGameResult(finalScore);
        }
    }
}

// 全局游戏实例
let game;

// 游戏控制函数
function startGame() {
    game.startGame();
}

function pauseGame() {
    game.pauseGame();
}

function resetGame() {
    game.resetGame();
}

function closeModal() {
    document.getElementById('gameOverModal').style.display = 'none';
    resetGame();
}

// 初始化游戏
window.addEventListener('load', () => {
    game = new SnakeGame();
    
    // 检查登录状态
    checkLoginStatus();
    
    // 加载排行榜
    loadLeaderboard();
});